import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '@/views/HomeView.vue'
import LoginView from '@/views/LoginView.vue'
import SetupView from '@/views/SetupView.vue'
import NginxConfigView from '@/views/NginxConfigView.vue'
import LogView from '@/views/LogView.vue'
import SSLView from '@/views/SSLView.vue'
import { useAuthStore } from '@/stores/auth'
import { authService } from '@/services/auth'
import DashboardView from '@/views/DashboardView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      meta: { requiresAuth: true },
      children: [
        {
          path: '',
          name: 'dashboard',
          component: DashboardView
        },
        {
          path: 'nginx/config',
          name: 'nginx-config',
          component: NginxConfigView
        },
        {
          path: "nginx/logs",
          name: "nginx-logs",
          component: LogView
        },
        {
          path: "nginx/ssl",
          name: "nginx-ssl",
          component: SSLView
        }
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView,
      meta: { requiresAuth: false }
    },
    {
      path: '/setup',
      name: 'setup',
      component: SetupView,
      meta: { requiresAuth: false }
    }
  ]
})

// 路由守卫
router.beforeEach(async (to) => {
  // 检查系统是否已安装
  if (to.name !== 'setup') {
    try {
      const { needsSetup: status } = await authService.checkStatus()
      if (status) {
        return { name: 'setup' }
      }
    } catch (error) {
      console.error('检查系统状态失败:', error)
      return { name: 'setup' }
    }
  }

  const authStore = useAuthStore()
  const token = localStorage.getItem('token')
  
  // 如果有 token 但没有用户信息，尝试获取用户信息
  if (token && !authStore.user) {
    try {
      await authStore.checkAuth()
    } catch (error) {
      // 如果获取用户信息失败，清除 token
      localStorage.removeItem('token')
      if (to.meta.requiresAuth !== false) {
        return { name: 'login' }
      }
    }
  }
  
  // 检查是否需要认证
  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    return { name: 'login' }
  }
  
  // 如果已登录，访问登录页则重定向到首页
  if (authStore.isAuthenticated && to.name === 'login') {
    return { name: 'home' }
  }
})

export default router 